/*
POP3 Protocol Handler

Copyright (C) 2007  Carlos Daniel Ruvalcaba Valenzuela <clsdaniel@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include <libfmail.h>
#include <odkutils.h>

char *demomsg = "From: Test John <testjohn@localhost>\n"
"To: test@localhost\n"
"Content-Type: text/plain\n"
"Date: Wed, 06 Jun 2007 15:21:21 -0700\n"
"Message-Id: <1181168481.15047.2.camel@localhost>\n"
"Mime-Version: 1.0\n"
"X-Mailer: Evolution 2.10.1 \n"
"Content-Transfer-Encoding: 7bit\n"
"\n"
"Test Mail!!";

const int POP3_PORT = 12001; //25;
const char CRLF[2] = {0x0D, 0x0A};

const int CMD_USER = 1;
const int CMD_PASS = 2;
const int CMD_STAT = 3;
const int CMD_LIST = 4;
const int CMD_RETR = 5;
const int CMD_DELE = 6;
const int CMD_NOOP = 7;
const int CMD_QUIT = 8;
const int CMD_RSET = 9;
const int CMD_TOP = 10;
const int CMD_CAPA = 10;

const char KEY_END_DATA[6] = {0x0D, 0x0A, '.', 0x0D, 0x0A, 0x00};

#define STATE_AUTH 			1
#define STATE_AUTH2 		2
#define STATE_TRANSACTION 	3
#define STATE_UPDATE  		4

int knhash(char v){
    if ((v >= 65) && (v <= 90))
        return v - 65;
    
    if (v == 95)
        return 26;
    
    if ((v >= 97) && (v <= 122))
        return v - 97;
    
    if (v == ' ')
        return -1;
    
    if (v == 0x0D)
        return -1;
        
    return 255;
}

class POP3Handler : public ProtocolHandler{
    SearchTree<int, 27, &knhash> cmdtree;
public:
    POP3Handler(){
        cmdtree.Insert("USER", 1);
        cmdtree.Insert("PASS", 2);
        cmdtree.Insert("STAT", 3);
        cmdtree.Insert("LIST", 4);
        cmdtree.Insert("RETR", 5);
        cmdtree.Insert("DELE", 6);
        cmdtree.Insert("NOOP", 7);
        cmdtree.Insert("QUIT", 8);
        cmdtree.Insert("RSET", 9);
        cmdtree.Insert("TOP", 10);
        cmdtree.Insert("CAPA", 11);
    }
    int Handle(Socket *s){
        char buffer[255];
        char userbuff[255];
        char outbuff[255];
        int r, i, j;
        int onrun, cmd, state;
    	odkRegex *reg;
        odkRegMatch *m;
        IPC *ipc;
        IPCMessage *msg;
        char *user, *pass;
        
        ipc = IPC::CreateIPC("socket://127.0.0.1:14000");
        
        reg = odk_regex_new("[\\w\\a]*\\s([\\w\\a]*)", 0, 0);
        s->Write("+OK FancyMail v0.1", 18);
        s->Write(CRLF, 2);
        
        state = STATE_AUTH;
        
        user = NULL;
        pass = NULL;
        
        onrun = 1;
	
        while (onrun){
		    memset(buffer, 0, 255);
    		r = s->Read(buffer, 255);
	    	
            try{
                cmd = cmdtree.Lookup(buffer);
            }catch (SearchNotFound){
                cmd = -1;
            }
            
		    if (cmd == CMD_QUIT){
			    printf("Got QUIT\n");
	    		s->Write( "+OK", 3);
    			s->Write( CRLF, 2);
			    state = STATE_UPDATE;
		    }
				
		    switch (state){
			    case STATE_AUTH:
				    if (cmd == CMD_USER){
                        
                        m = odk_regex_match(reg, buffer, 0);
                        user = odk_submatch_copy(buffer, m, 0);
					    printf("Got USERNAME: %s\n", user);
                        odk_match_free(m);
                        
    					s->Write( "+OK", 3);
	    				s->Write( CRLF, 2);
		    			state = STATE_AUTH2;
			    	}else{
				    	printf("INVALID [AUTH]: %s\n", buffer);
					    s->Write( "-ERR", 4);
    					s->Write( CRLF, 2);
	    			}
		    		break;
			    case STATE_AUTH2:
				    if (cmd == CMD_PASS){
                        
                        m = odk_regex_match(reg, buffer, 0);
                        
                        pass = odk_submatch_copy(buffer, m, 0);
                        odk_match_free(m);
                        
					    printf("Got Password: %s\n", pass);
                        
                        i = 0;
                        while (i < 10){
                            if (ipc->RequestIPC())
                                i = 10;
                        }
                        
                        msg = new IPCMessage("auth");
                        msg->PushParam(user);
                        msg->PushParam(pass);
                        ipc->PushMessage(msg);
                        
                        while(ipc->PeekMessage() == 0){
                        }
                        msg = ipc->PopMessage();
                        
                        ipc->CloseIPC();
                        
                        if (!strcmp(msg->GetMessageName(), "authok")){
                            s->Write( "+OK", 3);
    	    				s->Write( CRLF, 2);
                            state = STATE_TRANSACTION;
                        }else{
                            s->Write( "-ERR", 4);
        					s->Write(CRLF, 2);
    	    				state = STATE_AUTH;
    					}
		    			
			    	}else{
				    	printf("INVALID [AUTH2]: %s\n", buffer);
					    s->Write( "-ERR", 4);
    					s->Write(CRLF, 2);
	    				state = STATE_AUTH;
		    		}
			    	break;
    			case STATE_TRANSACTION:
	    			switch (cmd){
                    case CMD_STAT:
		    			printf("Got STAT Command\n");
			    		s->Write( "+OK 3 400", 9);
				    	s->Write( CRLF, 2);
                        break;
    				case CMD_LIST:
	    				printf("Got LIST Command: %s\n", buffer);
		    			s->Write( "+OK", 3);
			    		s->Write( CRLF, 2);
				    	
					    s->Write( "1 150", 5);
    					s->Write( CRLF, 2);
	    				
		    			s->Write( "2 150", 5);
			    		s->Write( CRLF, 2);
				    	
					    s->Write( "3 100", 5);
    					s->Write( CRLF, 2);
	    				s->Write( ".", 1);
		    			s->Write( CRLF, 2);
                        break;
			    	case CMD_RETR:
				    	printf("Got RETR Command: %s\n", buffer);
					    s->Write( "+OK 150 octets", 14);
    					s->Write( CRLF, 2);
	    				
		    			s->Write( demomsg, strlen(demomsg));
			    		
				    	s->Write( CRLF, 2);
					    s->Write( ".", 1);
    					s->Write( CRLF, 2);
                        break;
	    			case CMD_DELE:
		    			printf("Got DELE Command: %s\n", buffer);
			    		s->Write( "+OK", 3);
				    	s->Write( CRLF, 2);
                        break;
    				case CMD_NOOP:
	    				printf("Got NOOP Command\n");
		    			s->Write( "+OK", 3);
			    		s->Write( CRLF, 2);
                        break;
				    case CMD_RSET:
					    printf("Got RSET Command\n");
    					s->Write( "+OK", 3);
	    				s->Write( CRLF, 2);
		    		case CMD_TOP:
			    		printf("Got TOP Command: %s\n", buffer);
				    	for (i = strlen(buffer); i > 0; i--){
					    	if (buffer[i] == ' ')
						    	break;
    					}
	    				if (i >= 0){
		    				i = atoi((char*)(buffer + i));
			    		}else{
				    		i = 0;
					    }
    					s->Write( "+OK", 3);
	    				s->Write( CRLF, 2);
		    			
			    		j =0;
				    	for (r = 0; r < i; r++){
					    	sscanf((char*)(demomsg+j), "%s", buffer);
						    j = j + strlen(buffer);
    						s->Write( buffer, strlen(buffer));
	    					s->Write( CRLF, 2);
		    			}
			    		s->Write( ".", 1);
				    	s->Write( CRLF, 2);
                        break;
    				default:
	    				printf("INVALID [TRANS]: %s\n", buffer);
		    			s->Write( "-ERR", 4);
			    		s->Write( CRLF, 2);
				    }
    				break;
	    		case STATE_UPDATE:
		    		onrun = 0;
			    	break;
            }
        }	
	    printf("Closing Connection\n");
        s->Close();
    }
};

#ifdef STANDALONE
class SimpleLoad : public LoadHandler {
public:
	int Dispatch(Socket *sock, ProtocolHandler *ph){
		if (ph)
			return ph->Handle(sock);
		return 0;
	}
};

int main(int argc, char **argv){
	BaseServer *srv;
	SimpleLoad *lh;
	POP3Handler *pop3;

	pop3 = new POP3Handler();
	srv = new BaseServer(pop3, 12001);
	lh = new SimpleLoad();
	srv->SetLoadhandler(lh);
	srv->Listen();

	while(1){
		srv->Accept();
	}

	return 0;
}
#endif

extern "C"{
ProtocolHandler *plugin_protocol_load(){
    return new POP3Handler();
}
}
